package com.itjiange.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itjiange.springbootinit.annotation.AuthCheck;
import com.itjiange.springbootinit.bizmq.MyBIMessageProduce;
import com.itjiange.springbootinit.common.BaseResponse;
import com.itjiange.springbootinit.common.DeleteRequest;
import com.itjiange.springbootinit.common.ErrorCode;
import com.itjiange.springbootinit.common.ResultUtils;
import com.itjiange.springbootinit.constant.ChartConstant;
import com.itjiange.springbootinit.constant.CommonConstant;
import com.itjiange.springbootinit.constant.UserConstant;
import com.itjiange.springbootinit.exception.BusinessException;
import com.itjiange.springbootinit.exception.ThrowUtils;
import com.itjiange.springbootinit.manager.CosManager;
import com.itjiange.springbootinit.manager.RedisLimiterManager;
import com.itjiange.springbootinit.model.dto.ai.ChatResponse;
import com.itjiange.springbootinit.model.dto.chart.*;
import com.itjiange.springbootinit.model.entity.Chart;
import com.itjiange.springbootinit.model.entity.User;
import com.itjiange.springbootinit.model.enums.FileUploadBizEnum;
import com.itjiange.springbootinit.model.vo.BIMessageVO;
import com.itjiange.springbootinit.service.ChartService;
import com.itjiange.springbootinit.service.UserService;
import com.itjiange.springbootinit.utils.ChartAIUtils;
import com.itjiange.springbootinit.utils.ExcelUtils;
import com.itjiange.springbootinit.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 帖子接口
 *
 * @author itjiange
 * @from <a href="https://gitee.com/yijian-smiles">一健憨笑代码仓库</a>
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private CosManager cosManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private MyBIMessageProduce myBIMessageProduce;
    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * ai 图表生成
     *
     * @param multipartFile
     * @param createChartByAIRequest
     * @param request
     * @return
     */
    @PostMapping("/create")
    public BaseResponse<BIMessageVO> createChartByAI(@RequestPart("file") MultipartFile multipartFile,
                                                     CreateChartByAIRequest createChartByAIRequest, HttpServletRequest request) {
        String goal = createChartByAIRequest.getGoal();
        String chartName = createChartByAIRequest.getChartName();
        String chartType = createChartByAIRequest.getChartType();
        // 校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(chartName) && chartName.length() > 100, ErrorCode.PARAMS_ERROR, "图表名称过长");
        // 如果用户未登录则无法生成图表
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(ObjectUtil.isEmpty(loginUser), ErrorCode.OPERATION_ERROR, "用户未登录");
        // 限流
        redisLimiterManager.doRedisLimit("createChartByAI_" + loginUser.getId());
        // 文件校验
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long sizeMax = 1024 * 1024L;
        ThrowUtils.throwIf(sizeMax < size, ErrorCode.PARAMS_ERROR, "文件大小超过限制");
        // 校验文件后缀
        String suffix = FileUtil.getSuffix(originalFilename);
        ThrowUtils.throwIf(!"xlsx".equals(suffix), ErrorCode.PARAMS_ERROR, "文件格式错误");
        String csvData = ExcelUtils.excelTpCsv(multipartFile);
        // 用户输入语句
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append(goal);
        userInput.append("原始数据：")
                .append('\n')
                .append(csvData);
        if (StringUtils.isNotBlank(chartType)) {
            userInput.append("生成").append(chartType);
        }
//        ChatResponse chat = ChartAIUtils.chat(userInput.toString());
        String outputText = ChartAIUtils.chatGpt(userInput.toString());
        // 校验
//        String outputText = chat.getOutput().text;
        ThrowUtils.throwIf(StringUtils.isBlank(outputText), ErrorCode.PARAMS_ERROR, "AI 无响应");
        // 解析 AI 返回结果
        String[] split = outputText.split("【【【】】】");
        ThrowUtils.throwIf(split.length > 3, ErrorCode.PARAMS_ERROR, "AI 图表生成失败");

        String genChart = split[1].trim();
        String genResult = split[2].trim();

        // 封装图表对象，存入数据库中
        Chart chart = new Chart();
        chart.setChartName(chartName);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setStatus(ChartConstant.CHAT_STATE_SUCCEED);
        chart.setUserId(loginUser.getId());
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败");

        // 封装返回结果
        BIMessageVO biMessageVO = new BIMessageVO();
        biMessageVO.setGenChart(genChart);
        biMessageVO.setGenResult(genResult);

        return ResultUtils.success(biMessageVO);
    }

    /**
     * ai 图表异步生成
     *
     * @param multipartFile
     * @param createChartByAIRequest
     * @param request
     * @return
     */
    @PostMapping("/create/async")
    public BaseResponse<BIMessageVO> createAsyncChartByAI(@RequestPart("file") MultipartFile multipartFile,
                                                          CreateChartByAIRequest createChartByAIRequest, HttpServletRequest request) {
        String goal = createChartByAIRequest.getGoal();
        String chartName = createChartByAIRequest.getChartName();
        String chartType = createChartByAIRequest.getChartType();
        // 校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(chartName) && chartName.length() > 100, ErrorCode.PARAMS_ERROR, "图表名称过长");
        // 如果用户未登录则无法生成图表
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(ObjectUtil.isEmpty(loginUser), ErrorCode.OPERATION_ERROR, "用户未登录");
        // 限流
        redisLimiterManager.doRedisLimit("createChartByAI_" + loginUser.getId());
        // 文件校验
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long sizeMax = 1024 * 1024L;
        ThrowUtils.throwIf(sizeMax < size, ErrorCode.PARAMS_ERROR, "文件大小超过限制");
        // 校验文件后缀
        String suffix = FileUtil.getSuffix(originalFilename);
        ThrowUtils.throwIf(!"xlsx".equals(suffix), ErrorCode.PARAMS_ERROR, "文件格式错误");
        String csvData = ExcelUtils.excelTpCsv(multipartFile);

        // 封装图表对象，存入数据库中
        Chart chart = new Chart();
        chart.setChartName(chartName);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setStatus(ChartConstant.CHAT_STATE_WAIT);
        chart.setUserId(loginUser.getId());
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败");

        // 异步改造
        CompletableFuture.runAsync(() -> {
            // 将图表状态改为执行中
            Chart updateChart = new Chart();
            updateChart.setId(chart.getId());
            updateChart.setStatus(ChartConstant.CHAT_STATE_RUNNING);
            boolean flag = chartService.updateById(updateChart);
            if (!flag) {
                handleChartError(chart.getId(), "图表状态修改失败");
                return;
            }
            // 用户输入语句
            StringBuilder userInput = new StringBuilder();
            userInput.append("分析需求：").append(goal);
            userInput.append("原始数据：")
                    .append('\n')
                    .append(csvData);
            if (StringUtils.isNotBlank(chartType)) {
                userInput.append("生成").append(chartType);
            }
            ChatResponse chat = ChartAIUtils.chat(userInput.toString());
            // 校验
            String outputText = chat.getOutput().text;
            if (StringUtils.isBlank(outputText)) {
                handleChartError(chart.getId(), "AI 无响应");
                return;
            }
            // 解析 AI 返回结果
            String[] split = outputText.split("【【【】】】");
            if (split.length > 3) {
                handleChartError(chart.getId(), "AI 图表生成失败");
                return;
            }
            String genChart = split[1].trim();
            String genResult = split[2].trim();
            Chart updateChartResult = new Chart();
            updateChartResult.setId(chart.getId());
            updateChartResult.setGenChart(genChart);
            updateChartResult.setGenResult(genResult);
            updateChartResult.setStatus(ChartConstant.CHAT_STATE_SUCCEED);
            boolean resFlag = chartService.updateById(updateChartResult);
            if (!resFlag) {
                handleChartError(chart.getId(), "图表成功状态更新失败");
            }
        }, threadPoolExecutor);

        // 封装返回结果
        BIMessageVO biMessageVO = new BIMessageVO();
        biMessageVO.setChartId(chart.getId());

        return ResultUtils.success(biMessageVO);
    }

    @PostMapping("/create/async/mq")
    public BaseResponse<BIMessageVO> createAsyncChartByAIAndMq(@RequestPart("file") MultipartFile multipartFile,
                                                            CreateChartByAIRequest createChartByAIRequest, HttpServletRequest request) {
        String goal = createChartByAIRequest.getGoal();
        String chartName = createChartByAIRequest.getChartName();
        String chartType = createChartByAIRequest.getChartType();
        // 校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(chartName) && chartName.length() > 100, ErrorCode.PARAMS_ERROR, "图表名称过长");
        // 如果用户未登录则无法生成图表
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(ObjectUtil.isEmpty(loginUser), ErrorCode.OPERATION_ERROR, "用户未登录");
        // 限流
        redisLimiterManager.doRedisLimit("createChartByAI_" + loginUser.getId());
        // 文件校验
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long sizeMax = 1024 * 1024L;
        ThrowUtils.throwIf(sizeMax < size, ErrorCode.PARAMS_ERROR, "文件大小超过限制");
        // 校验文件后缀
        String suffix = FileUtil.getSuffix(originalFilename);
        ThrowUtils.throwIf(!"xlsx".equals(suffix), ErrorCode.PARAMS_ERROR, "文件格式错误");
        String csvData = ExcelUtils.excelTpCsv(multipartFile);

        // 封装图表对象，存入数据库中
        Chart chart = new Chart();
        chart.setChartName(chartName);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setStatus(ChartConstant.CHAT_STATE_WAIT);
        chart.setUserId(loginUser.getId());
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败");

        // 异步改造

        // TODO mq改造进行中
        // 发送消息到MQ
        myBIMessageProduce.sendMessage(String.valueOf(chart.getId()));

        // 封装返回结果
        BIMessageVO biMessageVO = new BIMessageVO();
        biMessageVO.setChartId(chart.getId());

        return ResultUtils.success(biMessageVO);
    }

    /**
     * 执行失败
     * @param id
     * @param execMessage
     */
    private void handleChartError(Long id, String execMessage) {
        // 更改图表状态为失败
        Chart updateChart = new Chart();
        updateChart.setId(id);
        updateChart.setStatus(ChartConstant.CHAT_STATE_FAILED);
        updateChart.setExecMessage(execMessage);
        boolean flag = chartService.updateById(updateChart);
        if (!flag) {
            log.info("图表：" + id + "，执行失败，execMessage：" + execMessage);
        }
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                     HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                       HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }


    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    private QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        Long id = chartQueryRequest.getId();
        String goal = chartQueryRequest.getGoal();
        String chartName = chartQueryRequest.getChartName();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        queryWrapper.eq(id != null && id != 0, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(goal), "goal", goal);
        queryWrapper.like(StringUtils.isNotBlank(chartName), "chartName", chartName);
        queryWrapper.eq(StringUtils.isNotBlank(chartType), "chartType", chartType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     * @param fileUploadBizEnum 业务类型
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 1M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }
}
